var xdIframe;
var y = 0;

//必须用 attachEvent, 否则监听无效
function addEvent(z, B, A) {
  if (z.attachEvent) {
    z.attachEvent("on" + B, A);
  }
  else {
      if (z.addEventListener) {
          z.addEventListener(B, A, false);
      }
      else {
          z["on" + B] = A;
      }
  }
}

function createAnotherIframe(callback) {
    var iframe = document.createElement('iframe');
    iframe.id = 'xd_iframe';
    iframe.src = 'http://127.0.0.1/templet/cross-domain/another-domain.html';

    addEvent(iframe, 'load', function() {
      callback()
    })
    document.body.insertBefore(iframe, document.body.firstChild)
    xdIframe = iframe;
}

var messagePoll = function(scope, key) {
  var d = '';

  function parseOption(val) {
    var options = val.split("^").pop().split("&");
    return {
      domain: options[0],
      data: window.unescape(options[1])
    }
  }

  function callback() {
    var val = scope[key];
    if (val != d) {
      d = val;
      clearInterval(timeInterval);
      messageHandler(parseOption(val))
    }
  }
  var timeInterval = setInterval(callback, 1000 / 20)
};



function sendMessage(options) {
  // debugger
  messagePoll(window, "name");
  console.log('xd外面的情况', document.domain, window.name)
  xdIframe.contentWindow.name = (new Date()).getTime() + (y++) + "^" + document.domain + "&" + window.escape(options);
}


function messageHandler() {

}

// 监听 message, 回调messageHandler



createAnotherIframe(function() {
  sendMessage(window._initCallbacks[0])
})